<template>
  <div class="cust-wrap">
    <div class="cust-content">
      <div class="cust-top">
        <el-row>
          <el-col :span="compare.isCompare ? 12 : 24">
            <div class="title">
              <i :class="showCust ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="toggleShow"></i>
              结果预览
              <span class="time" v-if="previewTime">更新时间：{{ previewTime }}</span>
            </div>
            <div class="count">
              <span class="count-icon"><icon-svg name="iconPersonal"></icon-svg></span>
              客户数：{{ grpTotal }}人
              <!-- <span class="line"></span>
          <span class="percent">在全量客户中占比3.2%</span> -->
            </div>
          </el-col>
          <transition name="el-zoom-in-right">
            <el-col :span="12" class="compare-col" v-if="compare.isCompare">
              <div class="compare-title">
                对比画像：
                <el-select v-model="compare.derivedTagId">
                  <el-option
                    v-for="item in compare.compareList"
                    :key="item.derivedTagId"
                    :value="item.derivedTagId"
                    :label="item.derivedTagNm"
                  ></el-option>
                </el-select>
                <span class="data-date">
                  历史版本：
                  <el-date-picker
                    type="month"
                    value-format="yyyyMM"
                    v-model="compare.dataDate"
                    placeholder="选择时间"
                    :picker-options="compare.pickOptions"
                  ></el-date-picker>
                </span>
                <el-button type="primary" size="mini" @click="changeCompare">确定</el-button>
              </div>
              <div class="count">
                <span class="count-icon"><icon-svg name="iconPersonal"></icon-svg></span>
                客户数：{{ compare.grpTotal }}人
                <!-- <span class="line"></span>
          <span class="percent">在全量客户中占比3.2%</span> -->
              </div>
            </el-col>
          </transition>
        </el-row>
        <div class="compare-handler" @click="toggleCompare" v-if="tmplId">
          <div class="compare-handler-wrap">
            <template v-if="!compare.isCompare">
              <icon-svg name="iconCompare"></icon-svg>
              <br />
              <span>对<br />比</span>
            </template>
            <template v-else>
              <i class="el-icon-close"></i>
              <br />
              <span>取<br />消</span>
            </template>
          </div>
        </div>
      </div>
      <el-collapse-transition>
        <div class="cust-config tag-scrollbar" @drop="copyDrop($event)" @dragover="allowDrag($event)" v-show="showCust">
          <template v-if="!grpFlter.length">
            <span class="tmpl-return" v-if="showTmplList || tmplId" @click="backTmpl">
              返回
            </span>
            <div class="config-wrap" v-if="!tmplId">
              <tmpl-list ref="tmplList" v-if="showTmplList" @callback="addTmpl"></tmpl-list>
              <template v-else>
                <div class="config-selector-wrap clearfix">
                  <div
                    class="config-selector"
                    @click="getTmplList"
                    @mouseenter="cust1_default = false"
                    @mouseleave="cust1_default = true"
                  >
                    <h4>使用已保存的画像模板快速创建</h4>
                    <img :src="cust1_default ? cust1 : cust1_hover" />
                    <p><i class="el-icon-plus"></i>创建客群画像</p>
                  </div>
                  <div
                    class="config-selector"
                    @click="
                      () => {
                        tmplId = -1
                      }
                    "
                    @mouseenter="cust2_default = false"
                    @mouseleave="cust2_default = true"
                  >
                    <h4>拖入自定义标签创建</h4>
                    <img :src="cust2_default ? cust2 : cust2_hover" />
                    <p><i class="el-icon-plus"></i>创建客群画像</p>
                  </div>
                </div>
              </template>
            </div>
            <div class="config-tips" v-else>
              <span>
                <i class="el-icon-plus"></i>
              </span>
              <br />
              将标签拖入此区域，添加客群画像
            </div>
          </template>
          <div v-else class="config-wrap">
            <div class="config-title">
              画像信息<span>拖入标签至此区域以增加画像</span>
              <span class="grp-icon save-icon" @click="showTempl()">
                <el-tooltip effect="dark" content="保存为画像模板" placement="top">
                  <icon-svg name="iconSave"></icon-svg>
                </el-tooltip>
              </span>
            </div>
            <div class="config-content">
              <el-row :gutter="20">
                <el-col
                  :span="compare.isCompare && compare.confirmCompare ? 24 : 12"
                  v-for="(item, index) in grpFlter"
                  :key="index"
                  class="map-item"
                >
                  <bar
                    v-if="item.mainGrp.graphType === 'bar' || item.mainGrp.graphType === 'stack'"
                    ref="factoryChart"
                    :grpFlter="
                      Object.assign({}, item, {
                        isCompare: compare.isCompare && compare.confirmCompare,
                        index: item.grpId || index
                      })
                    "
                    :grpTotal="{ grpTotal: grpTotal, compareTotal: compare.grpTotal }"
                    @editChart="editChart(item, index)"
                    @deleteChart="deleteChart(item.grpId || index)"
                    @export="exportResult(item)"
                    @downloadChart="downloadChart"
                    @handleDeep="handleDeep(item)"
                  />
                  <pie
                    v-if="item.mainGrp.graphType === 'pie' || item.mainGrp.graphType === 'circle'"
                    ref="factoryChart"
                    :grpFlter="
                      Object.assign({}, item, {
                        isCompare: compare.isCompare && compare.confirmCompare,
                        index: item.grpId || index
                      })
                    "
                    :grpTotal="{ grpTotal: grpTotal, compareTotal: compare.grpTotal }"
                    @editChart="editChart(item, index)"
                    @deleteChart="deleteChart(item.grpId || index)"
                    @export="exportResult(item)"
                    @downloadChart="downloadChart"
                    @handleDeep="handleDeep(item)"
                  />
                  <heat
                    v-if="item.mainGrp.graphType === 'heat'"
                    ref="factoryChart"
                    :grpFlter="
                      Object.assign({}, item, {
                        isCompare: compare.isCompare && compare.confirmCompare,
                        index: item.grpId || index
                      })
                    "
                    :grpTotal="{ grpTotal: grpTotal, compareTotal: compare.grpTotal }"
                    @editChart="editChart(item, index)"
                    @deleteChart="deleteChart(item.grpId || index)"
                    @export="exportResult(item)"
                    @downloadChart="downloadChart"
                    @handleDeep="handleDeep(item)"
                  />
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>
    <cust-drawer ref="custDrawer" @callback="refreshMap"></cust-drawer>
    <tag-tmpl-drawer ref="tmplDrawer"></tag-tmpl-drawer>
    <tag-deep-analyse ref="tagDeepAnalyse" @updateDrill="updateDrill"></tag-deep-analyse>
  </div>
</template>

<script>
import custDrawer from './factory-cust-drawer'
import tmplList from './grpfilter/grp-tmpl-list'
// import tmplDrawer from './grpfilter/grp-tmpl-drawer'
import bar from './charts/bar'
import pie from './charts/pie'
import heat from './charts/heat'
import utils from '@/plugins/utils'
const cust1 = require('@/assets/img/factory_cust1.png')
const cust1_hover = require('@/assets/img/factory_cust1_hover.png')
const cust2 = require('@/assets/img/factory_cust2.png')
const cust2_hover = require('@/assets/img/factory_cust2_hover.png')
export default {
  components: {
    custDrawer,
    tmplList,
    // tmplDrawer,
    bar,
    pie,
    heat
  },
  data() {
    return {
      loading: false,
      cust1: cust1,
      cust1_default: true,
      cust1_hover: cust1_hover,
      cust2: cust2,
      cust2_default: true,
      cust2_hover: cust2_hover,
      grpTotal: 0,
      grpFlter: [],
      profile: [],
      previewTime: '',
      compare: {
        isCompare: false,
        grpTotal: 0,
        compareList: [],
        derivedTagId: '',
        derivedTag: {},
        profile: [],
        dataDate: '',
        pickOptions: {
          disabledDate(time) {
            return time.getTime() > new Date().getTime()
          }
        },
        confirmCompare: false
      },
      showTmplList: false,
      tmplId: '',
      showCust: false
    }
  },
  created() {
    this.getCompareList()
  },
  methods: {
    getCompareList() {
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/getDerivedTagList'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          const full = {
            derivedTagId: '-1',
            derivedTag: '{"request":{"labGrps":{},"grpFlter":[]},"extra":{},"cache":{}}',
            derivedTagNm: '全量客户'
          }
          this.compare.compareList = [full, ...data.data]
        } else {
          // 失败后执行的操作
        }
      })
    },
    update(data) {
      this.grpTotal = data.grpTotal
      this.profile = data.profile
      if (data.grpFlter) this.grpFlter = data.grpFlter
      if (data.refreshTime) this.previewTime = data.runDat
      if (this.profile.length) this.tmplId = -1
      this.$nextTick(() => this.refreshChart())
    },
    updateTime() {
      this.previewTime = utils.formatDateTime(new Date())
    },
    isProfileLoading() {
      // 判断是否在加载中
      let isLoading = false
      const targets = this.$refs.factoryChart
      if (targets && targets.length) {
        targets.forEach(target => {
          if (target.loading) isLoading = true
        })
      }
      return isLoading
    },
    updateFlter(grpFlter) {
      this.grpFlter = grpFlter
      this.$nextTick(() => {
        const targets = this.$refs.factoryChart
        this.grpFlter.forEach((item, index) => {
          const parentForm = this.$parent.$parent
          let derivedTag = parentForm.getParams()
          if (parentForm.initLabs) parentForm.initLabs(derivedTag)
          const grpTarget = targets.find(chart => chart.grpFlter.grpId === item.grpId)
          grpTarget.setLoading()
          derivedTag.request.grpFlter = Array.of(derivedTag.request.grpFlter[index])
          let param = {
            derivedTagNm: this.$parent.$parent.editForm.title,
            derivedTag: JSON.stringify(derivedTag)
          }
          if (parentForm.editForm.derivedTagId) param.derivedTagId = parentForm.editForm.derivedTagId
          this.$ajax({
            url: this.$ajax.setUrl('tagFactory/getDeriveTagResult'),
            method: 'post',
            data: this.$ajax.setData(param),
            timeout: 0
          }).then(({ data }) => {
            if (data && data.code === '0') {
              parentForm.updatelabs(derivedTag.request.labGrps)
              grpTarget.refreshChart(
                data.data.profile && data.data.profile.length
                  ? data.data.profile[0]
                  : { grpId: item.grpId, wrong: true }
              )
              this.previewTime = data.data.runDat
              this.grpTotal = data.data.grpTotal
              // 判断profile是否有
              if (data.data.profile.length) {
                let fileIndex = this.profile.findIndex(profile => profile.grpId === data.data.profile[0].grpId)
                if (fileIndex < 0)
                  this.profile.push(
                    data.data.profile.length ? data.data.profile[0] : { grpId: data.data.profile[0].grpId, wrong: true }
                  )
                else {
                  this.profile[fileIndex] = data.data.profile.length
                    ? data.data.profile[0]
                    : { grpId: data.data.profile[0].grpId, wrong: true }
                }
              }
            } else {
              let fileIndex = this.profile.findIndex(profile => profile.grpId === item.grpId)
              if (fileIndex < 0) this.profile.push({ grpId: item.grpId, wrong: true })
              else {
                this.profile[fileIndex] = { grpId: item.grpId, wrong: true }
              }
              grpTarget.refreshChart({ grpId: item.grpId, wrong: true })
              // 判断是否在加载中
              let isLoading = false
              targets.forEach(target => {
                if (target.loading) isLoading = true
              })
              if (!isLoading) this.$message.error(data.data || data.msg)
            }
          })
          this.$nextTick(() => {
            if (this.compare.isCompare) {
              this.resetDate(parentForm.editForm.dataDate)
            }
          })
        })
      })
    },
    setTotalInfo(data) {
      this.previewTime = data.runDat
      this.grpTotal = data.grpTotal
    },
    refreshChart() {
      let targets = this.$refs.factoryChart
      if (targets) {
        targets.forEach(item => {
          let index = item.grpFlter.index
          let profile = this.profile.find(grpfile => grpfile.grpId === index)
          item.refreshChart(profile ? profile : { grpId: index, wrong: true })
          if (this.compare.derivedTagId && this.compare.isCompare) {
            let cprofile = this.compare.profile.find(grpfile => grpfile.grpId === index)
            item.refreshCompareChart(cprofile ? cprofile : { grpId: index, wrong: true })
          }
        })
      }
    },
    deleteChart(index) {
      this.$confirm('确定删除该画像？').then(() => {
        const grpIndex = this.grpFlter.findIndex(item => item.grpId === index)
        const proIndex = this.profile.findIndex(item => item.grpId === index)
        const comIndex = this.compare.profile.findIndex(item => item.grpId === index)
        if (grpIndex >= 0) this.grpFlter.splice(grpIndex, 1)
        if (proIndex >= 0) this.profile.splice(proIndex, 1)
        if (comIndex >= 0) this.compare.profile.splice(comIndex, 1)
        this.$nextTick(() => this.refreshChart())
      })
    },
    editChart(item, index) {
      let target = this.grpFlter.find(tag => tag.grpId === item.grpId)
      let params = {
        mainGrp: {
          tagNm: item.mainGrp.tagNm,
          groupName: target.mainGrp.groupName,
          tagCode: item.mainGrp.labId,
          valueType: item.mainGrp.valueType,
          labTbl: item.mainGrp.labTbl,
          labFldMap: item.mainGrp.labFldMap,
          labGrps: item.mainGrp.labGrps,
          rangeInfo: item.mainGrp.rangeInfo,
          graphType: target.mainGrp.graphType,
          enums: item.mainGrp.enums,
          enumType: item.mainGrp.enumType,
          enumVal: item.mainGrp.enumVal
        },
        type: 'edit',
        index: item.grpId || index
      }
      if (item.subGrp && item.subGrp.labId) {
        params.subGrp = {
          tagNm: item.subGrp.tagNm,
          groupName: target.mainGrp.groupName,
          tagCode: item.subGrp.labId,
          valueType: item.subGrp.valueType,
          labTbl: item.subGrp.labTbl,
          labFldMap: item.subGrp.labFldMap,
          labGrps: item.subGrp.labGrps || [],
          rangeInfo: item.subGrp.rangeInfo || {},
          graphType: target.mainGrp.graphType,
          enums: item.subGrp.enums
        }
      } else {
        if (
          (item.mainGrp.valueType == '6' || item.mainGrp.valueType == '7') &&
          item.numGrp &&
          item.numGrp.funcArray.length
        ) {
          params.numGrp = item.numGrp
        }
      }
      this.$refs.custDrawer.showDrawer(params)
    },
    allowDrag(event) {
      event.preventDefault()
    },
    copyDrop(event) {
      if (!this.tmplId) return
      event.preventDefault()
      const tagId = event.dataTransfer.getData('tagId')
      if (!tagId) return
      const tagNm = event.dataTransfer.getData('tagNm')
      const tagCode = event.dataTransfer.getData('tagCode')
      const valueType = event.dataTransfer.getData('valueType')
      const labTbl = event.dataTransfer.getData('labTbl')
      const labFldMap = event.dataTransfer.getData('labFldMap')
      const enums = JSON.parse(event.dataTransfer.getData('enums'))
      const labId = event.dataTransfer.getData('tagCode')
      const isDerLabel = event.dataTransfer.getData('isDerLabel')
      if (Number(isDerLabel)) {
        this.$message.info('计算型标签不能作为客户画像！')
        return
      }
      if (valueType === '2') {
        this.$message.info('不能添加字符型标签画像')
        return
      }
      // 判断是否双维度
      let nodes = []
      let target = event.target
      while (!target.classList.contains('cust-config')) {
        nodes.push(target)
        target = target.parentNode
      }
      let isDimen = false
      let chart
      nodes.forEach(item => {
        if (item.classList.contains('factory-cust-chart')) {
          isDimen = true
          chart = item
        }
      })
      if (isDimen) {
        // 添加双维度画像
        const index = Number(chart.getAttribute('index'))
        const grpIndex = this.grpFlter.findIndex(item => item.grpId === index)
        if (this.grpFlter[grpIndex].subGrp && this.grpFlter[grpIndex].subGrp.labId) {
          this.$message.info('最多只能设计为二维画像！')
          return
        }
        if (this.grpFlter[grpIndex].numGrp && this.grpFlter[grpIndex].numGrp.funcArray.length) {
          this.$message.info('指标型画像不能添加二维画像！')
          return
        }
        let params = {
          grpId: index,
          mainGrp: this.grpFlter[grpIndex].mainGrp,
          subGrp: {
            labId,
            tagNm,
            tagCode,
            valueType,
            labTbl,
            labFldMap,
            enums
          }
        }
        this.editChart(params, index)
      } else {
        // 添加单纬度画像
        this.addCust({
          tagNm,
          tagCode,
          valueType,
          labTbl,
          labFldMap,
          enums
        })
      }
    },
    addCust(config) {
      if (config.isDerLabel) {
        this.$message.info('计算型标签不能作为客户画像！')
        return
      }
      let ids = []
      this.grpFlter.forEach(item => ids.push(Number(item.grpId)))
      this.$refs.custDrawer.showDrawer({
        mainGrp: {
          tagNm: config.tagNm,
          tagCode: config.tagCode,
          valueType: config.valueType,
          labTbl: config.labTbl,
          labFldMap: config.labFldMap,
          index: ids.length ? Math.max(...ids) + 1 : 1,
          enums: config.enums
        },
        type: 'add',
        index: ids.length ? Math.max(...ids) + 1 : 1
      })
    },
    refreshMap(result) {
      const grpIndex = this.grpFlter.findIndex(item => item.grpId === result.grpId)
      if (grpIndex >= 0) this.grpFlter[grpIndex] = result
      else this.grpFlter.push(result)
      this.$emit('callback', this.grpFlter)
      let derivedTag = this.$parent.$parent.getParams()
      if (this.$parent.$parent.initLabs) this.$parent.$parent.initLabs(derivedTag)
      derivedTag.request.grpFlter = [
        {
          grpId: result.grpId,
          mainGrp: {
            labId: result.mainGrp.labId,
            groupTyp: result.mainGrp.groupTyp,
            labGrps: result.mainGrp.labGrps
          }
        }
      ]
      if (result.subGrp && result.subGrp.labId) {
        derivedTag.request.grpFlter[0].subGrp = {
          labId: result.subGrp.labId,
          groupTyp: result.subGrp.groupTyp,
          labGrps: result.subGrp.labGrps
        }
      } else {
        if (
          (result.mainGrp.valueType == '6' || result.mainGrp.valueType == '7') &&
          result.numGrp &&
          result.numGrp.funcArray.length
        ) {
          derivedTag.request.grpFlter[0].numGrp = result.numGrp
        }
      }
      let param = {
        derivedTagNm: this.$parent.$parent.editForm.title,
        derivedTag: JSON.stringify(derivedTag)
      }
      if (this.$parent.$parent.editForm.derivedTagId) param.derivedTagId = this.$parent.$parent.editForm.derivedTagId
      this.loading = true
      this.$nextTick(() => {
        const chart = this.$refs.factoryChart
        const chartIndex = chart.findIndex(item => item.grpFlter.grpId === result.grpId)
        chart[chartIndex].setLoading()
        this.$ajax({
          url: this.$ajax.setUrl('tagFactory/getDeriveTagResult'),
          method: 'post',
          data: this.$ajax.setData(param),
          timeout: 0
        }).then(({ data }) => {
          if (data && data.code === '0') {
            let fileIndex = this.profile.findIndex(item => item.grpId === result.grpId)
            if (fileIndex < 0)
              this.profile.push(data.data.profile.length ? data.data.profile[0] : { grpId: result.grpId, wrong: true })
            else {
              this.profile[fileIndex] = data.data.profile.length
                ? data.data.profile[0]
                : { grpId: result.grpId, wrong: true }
            }
            this.previewTime = data.data.runDat
            this.grpTotal = data.data.grpTotal
            chart[chartIndex].refreshChart(
              data.data.profile.length ? data.data.profile[0] : { grpId: result.grpId, wrong: true }
            )
            if (this.compare.isCompare) this.refreshCompareMap(result)
          } else {
            const grpIndex = this.grpFlter.findIndex(item => item.grpId === result.grpId)
            if (grpIndex >= 0) {
              if (this.grpFlter[grpIndex].subGrp && this.grpFlter[grpIndex].subGrp.labId) {
                // 如果是二维画像，值删除二维画像
                delete this.grpFlter[grpIndex].subGrp
              } else this.grpFlter.splice(grpIndex, 1)
            }
            this.$message.error(data.data || data.msg)
            this.loading = false
          }
          if (!this.compare.isCompare) this.loading = false
        })
      })
      this.$forceUpdate()
    },
    refreshCompareMap(result) {
      let derivedTag = {
        cache: JSON.parse(this.compare.derivedTag.derivedTag).cache,
        extra: {},
        request: {
          dataDate: this.$parent.$parent.editForm.dataDate,
          grpFlter: [],
          labGrps: JSON.parse(this.compare.derivedTag.derivedTag).request.labGrps
        }
      }
      if (this.$parent.$parent.drillGrps && this.$parent.$parent.drillGrps.length) {
        derivedTag.request.drillGrps = this.$parent.$parent.drillGrps
        this.$parent.$parent.drillGrps.forEach(drillArray => {
          drillArray.forEach(drill => {
            if (!Object.keys(derivedTag.cache).find(label => label === drill.mainDrill.labId)) {
              derivedTag.cache[drill.mainDrill.labId] = {
                tagNm: drill.mainDrill.tagNm
              }
            }
            if (drill.subDrill) {
              if (!Object.keys(derivedTag.cache).find(label => label === drill.subDrill.labId)) {
                derivedTag.cache[drill.subDrill.labId] = {
                  tagNm: drill.subDrill.tagNm
                }
              }
            }
          })
        })
      }
      derivedTag.request.grpFlter = [
        {
          grpId: result.grpId,
          mainGrp: {
            labId: result.mainGrp.labId,
            groupTyp: result.mainGrp.groupTyp,
            labGrps: result.mainGrp.labGrps
          }
        }
      ]
      derivedTag.extra[result.grpId] = {
        [result.mainGrp.labId]: {
          groupName: result.mainGrp.groupName,
          groupTyp: result.mainGrp.groupTyp,
          graphType: result.mainGrp.graphType,
          labTbl: result.mainGrp.labTbl,
          labFldMap: result.mainGrp.labFldMap,
          rangeInfo: result.mainGrp.rangeInfo,
          valueType: result.mainGrp.valueType,
          enumType: result.mainGrp.enumType || '',
          enumVal: result.mainGrp.enumVal || ''
        }
      }
      if (!Object.keys(derivedTag.cache).find(label => label === result.mainGrp.labId)) {
        derivedTag.cache[result.mainGrp.labId] = {
          tagNm: result.mainGrp.tagNm
        }
      }
      if (result.subGrp && result.subGrp.labId) {
        derivedTag.request.grpFlter[0].subGrp = {
          labId: result.subGrp.labId,
          groupTyp: result.subGrp.groupTyp,
          labGrps: result.subGrp.labGrps
        }
        derivedTag.extra[result.grpId][result.subGrp.labId] = {
          groupName: result.subGrp.groupName,
          groupTyp: result.subGrp.groupTyp,
          graphType: result.subGrp.graphType,
          labTbl: result.subGrp.labTbl,
          labFldMap: result.subGrp.labFldMap,
          rangeInfo: result.subGrp.rangeInfo,
          valueType: result.subGrp.valueType
        }
        if (!Object.keys(derivedTag.cache).find(label => label === result.subGrp.labId)) {
          derivedTag.cache[result.subGrp.labId] = {
            tagNm: result.subGrp.tagNm
          }
        }
      } else {
        if (
          (result.mainGrp.valueType == '6' || result.mainGrp.valueType == '7') &&
          result.numGrp &&
          result.numGrp.funcArray.length
        ) {
          derivedTag.request.grpFlter[0].numGrp = result.numGrp
        }
      }
      let param = {
        derivedTagNm: this.compare.derivedTag.derivedTagNm,
        derivedTag: JSON.stringify(derivedTag),
        derivedTagId: this.compare.derivedTag.derivedTagId
      }
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/getDeriveTagResult'),
        method: 'post',
        data: this.$ajax.setData(param),
        timeout: 0
      }).then(({ data }) => {
        if (data && data.code === '0') {
          const fileIndex = this.compare.profile.findIndex(item => item.grpId === result.grpId)
          if (fileIndex < 0)
            this.compare.profile.push(
              data.data.profile.length ? data.data.profile[0] : { grpId: result.grpId, wrong: true }
            )
          else {
            this.compare.profile[fileIndex] = data.data.profile.length
              ? data.data.profile[0]
              : { grpId: result.grpId, wrong: true }
          }
          this.$nextTick(() => {
            const chart = this.$refs.factoryChart
            const newIndex = chart.findIndex(item => item.grpFlter.grpId === result.grpId)
            if (newIndex >= 0)
              chart[newIndex].refreshCompareChart(
                data.data.profile.length ? data.data.profile[0] : { grpId: result.grpId, wrong: true }
              )
          })
        } else {
          let fileIndex = this.compare.profile.findIndex(profile => profile.grpId === result.grpId)
          if (fileIndex < 0) this.profile.push({ grpId: result.grpId, wrong: true })
          else {
            this.profile[fileIndex] = { grpId: result.grpId, wrong: true }
          }
          this.$nextTick(() => {
            const chart = this.$refs.factoryChart
            const newIndex = chart.findIndex(item => item.grpFlter.grpId === result.grpId)
            if (newIndex >= 0) chart[newIndex].refreshCompareChart({ grpId: result.grpId, wrong: true })
          })
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    toggleCompare() {
      this.compare.isCompare = !this.compare.isCompare
      this.refreshChart()
    },
    changeCompare() {
      let compareTag = this.compare.compareList.find(item => item.derivedTagId === this.compare.derivedTagId)
      const targets = this.$refs.factoryChart
      this.compare.confirmCompare = true
      if (!compareTag) {
        compareTag = this.compare.compareList[0]
        this.compare.derivedTagId = compareTag.derivedTagId
      }
      let derivedTag = {
        cache: JSON.parse(compareTag.derivedTag).cache,
        extra: {},
        request: {
          dataDate: this.compare.dataDate,
          grpFlter: [],
          labGrps: JSON.parse(compareTag.derivedTag).request.labGrps
        }
      }
      if (this.$parent.$parent.drillGrps && this.$parent.$parent.drillGrps.length) {
        derivedTag.request.drillGrps = this.$parent.$parent.drillGrps
        this.$parent.$parent.drillGrps.forEach(drillArray => {
          drillArray.forEach(drill => {
            if (!Object.keys(derivedTag.cache).find(label => label === drill.mainDrill.labId)) {
              derivedTag.cache[drill.mainDrill.labId] = {
                tagNm: drill.mainDrill.tagNm
              }
            }
            if (drill.subDrill) {
              if (!Object.keys(derivedTag.cache).find(label => label === drill.subDrill.labId)) {
                derivedTag.cache[drill.subDrill.labId] = {
                  tagNm: drill.subDrill.tagNm
                }
              }
            }
          })
        })
      }
      this.grpFlter.forEach((item, index) => {
        const grpTarget = targets.find(chart => chart.grpFlter.grpId === item.grpId)
        grpTarget.setLoading('compare')
        derivedTag.request.grpFlter = [
          {
            grpId: item.grpId || index,
            mainGrp: {
              labId: item.mainGrp.labId,
              groupTyp: item.mainGrp.groupTyp,
              labGrps: item.mainGrp.labGrps
            }
          }
        ]
        derivedTag.extra[item.grpId || index] = {
          [item.mainGrp.labId]: {
            groupName: item.mainGrp.groupName,
            groupTyp: item.mainGrp.groupTyp,
            graphType: item.mainGrp.graphType,
            labTbl: item.mainGrp.labTbl,
            labFldMap: item.mainGrp.labFldMap,
            rangeInfo: item.mainGrp.rangeInfo,
            valueType: item.mainGrp.valueType,
            enumType: item.mainGrp.enumType || '',
            enumVal: item.mainGrp.enumVal || ''
          }
        }
        if (!Object.keys(derivedTag.cache).find(label => label === item.mainGrp.labId)) {
          derivedTag.cache[item.mainGrp.labId] = {
            tagNm: item.mainGrp.tagNm
          }
        }
        if (item.subGrp && item.subGrp.labId) {
          derivedTag.request.grpFlter[0].subGrp = {
            labId: item.subGrp.labId,
            groupTyp: item.subGrp.groupTyp,
            labGrps: item.subGrp.labGrps
          }
          derivedTag.extra[item.grpId || index][item.subGrp.labId] = {
            groupName: item.subGrp.groupName,
            groupTyp: item.subGrp.groupTyp,
            graphType: item.subGrp.graphType,
            labTbl: item.subGrp.labTbl,
            labFldMap: item.subGrp.labFldMap,
            rangeInfo: item.subGrp.rangeInfo,
            valueType: item.subGrp.valueType
          }
          if (!Object.keys(derivedTag.cache).find(label => label === item.subGrp.labId)) {
            derivedTag.cache[item.subGrp.labId] = {
              tagNm: item.subGrp.tagNm
            }
          }
        } else {
          if (
            (item.mainGrp.valueType == '6' || item.mainGrp.valueType == '7') &&
            item.numGrp &&
            item.numGrp.funcArray.length
          ) {
            derivedTag.request.grpFlter[0].numGrp = item.numGrp
          }
        }
        let param = {
          derivedTagNm: compareTag.derivedTagNm,
          derivedTag: JSON.stringify(derivedTag),
          derivedTagId: compareTag.derivedTagId
        }
        this.compare.derivedTag.derivedTagNm = compareTag.derivedTagNm
        this.compare.derivedTag.derivedTagId = compareTag.derivedTagId
        this.compare.derivedTag.derivedTag = JSON.stringify(derivedTag)
        this.loading = true
        this.$ajax({
          url: this.$ajax.setUrl('tagFactory/getDeriveTagResult'),
          method: 'post',
          data: this.$ajax.setData(param)
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.compare.grpTotal = data.data.grpTotal
            grpTarget.refreshCompareChart(
              data.data.profile.length ? data.data.profile[0] : { grpId: item.grpId, wrong: true }
            )
            const fileIndex = this.compare.profile.findIndex(file => file.grpId === item.grpId)
            if (fileIndex < 0)
              this.compare.profile.push(
                data.data.profile.length ? data.data.profile[0] : { grpId: item.grpId, wrong: true }
              )
            else {
              this.compare.profile[fileIndex] = data.data.profile.length
                ? data.data.profile[0]
                : { grpId: item.grpId, wrong: true }
            }
          } else {
            let fileIndex = this.compare.profile.findIndex(profile => profile.grpId === item.grpId)
            if (fileIndex < 0) this.profile.push({ grpId: item.grpId, wrong: true })
            else {
              this.profile[fileIndex] = { grpId: item.grpId, wrong: true }
            }
            grpTarget.refreshCompareChart({ grpId: item.grpId, wrong: true })
            // 判断是否在加载中
            let isLoading = false
            targets.forEach(target => {
              if (target.compare.loading) isLoading = true
            })
            if (!isLoading) this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    getTmplList() {
      let flag = true
      this.$parent.validate(valid => {
        if (valid) flag = true
        else flag = false
      })
      if (flag) {
        this.showTmplList = true
        this.$nextTick(() => this.$refs.tmplList.getList())
      } else this.$message.info('标签组合逻辑需全部填写！')
    },
    showTempl() {
      if (!this.grpFlter.length) this.$message.error('请拖入画像')
      let grpTmpl = []
      this.grpFlter.forEach((item, index) => {
        if (!grpTmpl.find(grpItem => grpItem.grpId === item.grpId))
          grpTmpl.push({
            grpId: item.grpId,
            mainGrp: {
              graphType: item.mainGrp.graphType,
              groupName: item.mainGrp.groupName,
              labId: item.mainGrp.labId,
              groupTyp: item.mainGrp.groupTyp,
              labTbl: item.mainGrp.labTbl,
              labFldMap: item.mainGrp.labFldMap,
              rangeInfo: item.mainGrp.rangeInfo,
              labGrps: item.mainGrp.labGrps,
              tagNm: item.mainGrp.tagNm,
              valueType: item.mainGrp.valueType,
              enums: item.mainGrp.enums,
              enumType: item.mainGrp.enumType,
              enumVal: item.mainGrp.enumVal
            }
          })
        if (item.subGrp && item.subGrp.labId) {
          const grpIndex = grpTmpl.findIndex(tag => tag.grpId === item.grpId)
          grpTmpl[grpIndex].subGrp = {
            graphType: item.subGrp.graphType,
            groupName: item.subGrp.groupName,
            labId: item.subGrp.labId,
            groupTyp: item.subGrp.groupTyp,
            labTbl: item.subGrp.labTbl,
            labFldMap: item.subGrp.labFldMap,
            rangeInfo: item.subGrp.rangeInfo,
            labGrps: item.subGrp.labGrps,
            tagNm: item.subGrp.tagNm,
            valueType: item.subGrp.valueType,
            enums: item.subGrp.enums
          }
        } else {
          if (
            (item.mainGrp.valueType == '6' || item.mainGrp.valueType == '7') &&
            item.numGrp &&
            item.numGrp.funcArray.length
          ) {
            grpTmpl[index].numGrp = item.numGrp
          }
        }
      })
      this.$refs.tmplDrawer.showDrawer({
        json: JSON.stringify(grpTmpl)
      })
    },
    addTmpl(tmpl) {
      this.tmplId = tmpl.tmplId
      this.$emit('readTmpl', tmpl.tmplJson)
    },
    backTmpl() {
      this.tmplId = ''
      this.showTmplList = false
    },
    exportResult(item) {
      const profile = this.profile.find(profile => profile.grpId === item.grpId)
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/downloadImageTmpl'),
        method: 'post',
        data: this.$ajax.setData({
          grpResults: profile.labGrps,
          tmplNm: profile.groupName
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$message.success(data.msg)
          this.$dlFile(data.data)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    downloadChart(arg) {
      let url = arg.chart.getDataURL({ backgroundColor: '#fff' })
      let link = document.createElement('a')
      let evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true)
      link.download = arg.name + '.png'
      link.href = url
      link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
    },
    resetDate(date) {
      this.compare.dataDate = date
      this.changeCompare()
    },
    toggleShow() {
      this.showCust = !this.showCust
    },
    handleDeep(item) {
      let profile = this.profile.find(grpfile => grpfile.grpId === item.grpId)
      this.$refs.tagDeepAnalyse.showDialog(profile, item, this.grpTotal)
    },
    updateDrill(drillGrps) {
      this.$parent.$parent.updateDrill(drillGrps)
    }
  }
}
</script>

<style lang="scss">
@import './factory-cust.scss';
</style>
